'''
Created on Feb 25, 2009

@author: whaleyr
'''
import os
import gradeProcs
import view
from models import Assignment,Course

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

from django import http
from django import shortcuts

class AssignmentForm(djangoforms.ModelForm):
  class Meta:
    model = Assignment
    exclude = ["course"]

def new(request):
  """Create an assignment."""
  user = users.GetCurrentUser()
  assignment=None
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a course')
  if not request.POST:
    return http.HttpNoResponseForbidden('No assignment data supplied')
  form = AssignmentForm(data=request.POST or None, instance=assignment)
  errors = form.errors
  if not errors:
    try:
      assignment = form.save(commit=False)
      assignment.course = Course.get(db.Key.from_path(Course.kind(), int(request.POST['courseid'])))
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return http.HttpNoResponseForbidden('Error with assignment data supplied')
  assignment.put()
  gradeProcs.gradeRecalc(assignment.course)
  return view.course.view(request, int(request.POST['courseid']))

def delete(request, assignment_id):
  """ Delete an assignment """
  user = users.GetCurrentUser()
  if assignment_id:
    assignment = Assignment.get(db.Key.from_path(Assignment.kind(), int(assignment_id)))
    if assignment is None:
      return http.HttpResponseNotFound('No assignment exists with that key (%r)' % assignment_id)
    assignment.delete()
    gradeProcs.gradeRecalc(assignment.course)
    return http.HttpResponseRedirect('/viewCourse/%r' % int(assignment.course.key().id()))
  return http.HttpResponseNotFound('Error deleting assignment %r' % assignment_id)

def edit(request, assignment_id):
  """Create or edit an assignment.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit an assignemnt')
  assignment = None
  if assignment_id:
    assignment = Assignment.get(db.Key.from_path(Assignment.kind(), int(assignment_id)))
    if assignment is None:
      return http.HttpResponseNotFound('No assignment exists with that key (%r)' %
                                       assignment_id)
  form = AssignmentForm(data=request.POST or None, instance=assignment)
  if not request.POST:
    return respond(request, user, 'assignment', {'form': form, 'assignment': assignment})
  errors = form.errors
  if not errors:
    try:
      assignment = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'assignment', {'form': form, 'assignment': assignment})
  assignment.put()
  gradeProcs.gradeRecalc(assignment.course)
  return http.HttpResponseRedirect('/viewCourse/%r' % int(assignment.course.key().id()))

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)
